package com.yohann.algorithm.binarySearch;

/**
 * <p>
 * 二分查找
 * </p>
 *
 * @author Yohann
 * @since 2021/1/14 21:00
 */
public class BinarySearch {
    public static void main(String[] args) {
        int[] arr = {1, 3, 8, 10, 11, 67, 100};
        int i = binarySearch(arr, 1);
        System.out.println(i);
    }

    /**
     * 二分查找非递归实现
     *
     * @param arr    数组范围
     * @param target 目标值
     * @return 目标索引值
     */
    public static int binarySearch(int[] arr, int target) {
        int left = 0;
        int right = arr.length - 1;

        while (left <= right) {
            int middle = (left + right) / 2;

            if (arr[middle] == target) {
                return middle;
            } else if (arr[middle] > target) {
                right = middle - 1;
            } else {
                left = middle + 1;
            }
        }

        return -1;
    }
}